﻿using CommonServiceLocator;
using GalaSoft.MvvmLight.CommandWpf;
using HuiZe.education.Common;
using HuiZe.education.Model;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using HuiZe.education.View;

namespace HuiZe.education.ViewModel
{
    public class StudentViewModel : ViewModelBase
    {
        public string SearchName { get; set; }
        public StudentView studentView { get; set; }
        //在校状态
        public ObservableCollection<CommonModel> StuStatus { get; set; }
        //班级
        public ObservableCollection<CommonModel> StuClasses { get; set; }

        public ObservableCollection<StudentModel> Students { get; set; }

        public RelayCommand AddCommand { get { return new RelayCommand(AddStudent); } }

        //public StudentViewModel studentViewModel { get; set; } = new StudentViewModel();
        public StudentModel studentModel { get; set; } = new StudentModel();
        public StudentModel QuerystudentModel { get; set; } = new StudentModel();
        public StudentModel studentModel2 { get; set; } = new StudentModel();
        public RelayCommand DeleteCommand { get { return new RelayCommand(DeleteStudent); } }
        public ErrorMsgModel ErrorMsg { get; set; } = new ErrorMsgModel();

        public ObservableCollection<MessageModel> Messages { get; set; }
        public int StudentId { get; set; }

        public int pageCount { get; set; }
        public StudentViewModel()
        {
            getGradesList();
            GetStudentList(1);


            if (IsInDesignMode)
            {
                //Students = new ObservableCollection<StudentModel>()
                //{
                //   new StudentModel()
                //   {
                //       StuName="erjker",
                //       ParentName="测试1" ,
                //       StuSex=1,
                //       StuStatus=1,
                //       StuClass="三年一班",
                //       StuNo="1234",
                //       ParentMobile="1122233333"
                //   }
                //};
            }
            //Students = new ObservableCollection<StudentModel>()
            //    {
            //       new StudentModel()
            //       {
            //           StuName="erjker",
            //           ParentName="测试1" ,
            //           StuSex=1,
            //           StuStatus=1,
            //           StuClass="三年一班",
            //           StuNo="1234",
            //           ParentMobile="1122233333"
            //       }
            //};

            //StuClasses = new ObservableCollection<CommonModel>()
            //  {
            //      new CommonModel(){ Index=0,Title="一年二班" },
            //      new CommonModel(){ Index=1,Title="三年四班"},
            //  };


            StuStatus = new ObservableCollection<CommonModel>()
              {
                  new CommonModel(){ Index=0,Title="在校" },
                  new CommonModel(){ Index=1,Title="离校"},
              };




        }


        public void GetStudentList(int PageIndex)
        {
            int gradid = 0;
            if (QuerystudentModel.StuName != null || QuerystudentModel.StuClass != null)
            {
                List<CommonModel> graditem = StuClasses.Where(x => x.Title.Equals(QuerystudentModel.StuClass)).ToList();
                if (graditem != null && graditem.Count > 0)
                {
                    CommonModel common = graditem[0];
                    gradid = common.Index;
                }
            }
            //Students.Clear();
            ReqStudentPamrm pamrm = new ReqStudentPamrm
            {
                page = PageIndex,
                limit = 10,
                token = HuiZeeducation.Instance.UserInfo.token,
                keyword = QuerystudentModel.StuName == null ? "" : QuerystudentModel.StuName,
                grades_id = gradid,
            };
            string data = JsonHelper.ToJson(pamrm);


            var result = Request<ReqStudentList>("/api/student/index", data, "学生列表");
            if (result.Item1)
            {
                pageCount = result.Item2.data.last_page;
                Students = new ObservableCollection<StudentModel>();
                var students = result.Item2.data.data;
                foreach (var student in students)
                {
                    List<CommonModel> graditem = StuClasses.Where(x => x.Index.ToString().Equals(student.grades_id)).ToList();
                    string classText = "";
                    if (graditem != null&& graditem.Count>0)
                    {
                        CommonModel common = graditem[0];
                        classText = common.Title;

                    }
                    var studentModel =
                    new StudentModel()
                    {
                        id = student.id,
                        ClassId = student.grades_id,
                        StuName = student.name,
                        ParentName = student.parent_name,
                        StuSex = Convert.ToInt32(student.sex == "男" ? 1 : 2),
                        StuStatus = Convert.ToInt32(student.status == "在校" ? 1 : 2),
                        StrStuStatus2 = student.status,
                        studentSex = student.sex,
                        StuClass = classText,
                        student_no = student.student_no.ToString(),
                        ParentMobile = student.parent_phone == "0" ? "" : student.parent_phone
                    };
                    Students.Add(studentModel);
                }
            }
            else
            {

            }


        }

        public bool IsTelephone(string str_telephone)
        {
            if (str_telephone.Length == 11)
                return System.Text.RegularExpressions.Regex.IsMatch(str_telephone, @"^[1]+[3,4,5,7,8,9]+\d{9}");

            return false;

        }

        public void AddStudent()
        {

            if (string.IsNullOrEmpty(studentModel.StuName) || string.IsNullOrEmpty(studentModel.student_no) || studentModel.ClassModel.Index <= 0)
            {
                //ErrorMsg.LoginMobileError = "学生姓名不能为空";
                ShowDialogView("学生姓名，学号，班级为必填项!");
                return;
            }
            //if (IsTelephone(studentModel.ParentMobile)|| studentModel.ParentMobile.Length > 15)
            //{
            //ErrorMsg.LoginMobileError = "请输入正确手机号";
            //    ShowDialogView("请输入正确手机号!");
            //    return;
            //}
            //if (studentModel.student_no.Length>10)
            //{
            ///ErrorMsg.LoginMobileError = "请输入正确学号";
            //ShowDialogView("请输入正确学号!");
            //return;
            //}


            if (StudentId > 0)
            {
                //修改
                studentModel.id = StudentId;
                editStudentModel editModel = new editStudentModel
                {
                    id = StudentId,
                    token = HuiZeeducation.Instance.UserInfo.token,
                    name = studentModel.StuName,
                    grades_id = studentModel.ClassModel.Index,
                    student_no = studentModel.student_no,
                    sex = studentModel.StuSex,
                    status = studentModel.StrStuStatus == "在校" ? 1 : 2,
                    parent_name = studentModel.ParentName,


                };
                if (studentModel.ParentMobile != "")
                {
                    editModel.parent_phone = studentModel.ParentMobile;
                }
                else
                {
                    editModel.parent_phone = null;
                }


                string data = JsonHelper.ToJson(editModel);
                var result = Request<ReqStudentModel>("/api/student/editStudent", data, "修改学生");
                if (result.Item1)
                {
                    ShowDialogView("修改成功!");
                    GetStudentList(1);
                    studentView.UpdatePager();

                }
                else
                {
                    if (result.Item2 != null)
                        ShowDialogView(result.Item2.msg);
                }

            }
            else
            {
                //添加
                AddStudentModel editModel = new AddStudentModel
                {

                    token = HuiZeeducation.Instance.UserInfo.token,
                    student_no = studentModel.student_no,
                    name = studentModel.StuName,
                    grades_id = studentModel.ClassModel.Index,
                    sex = studentModel.StuSex,
                    status = studentModel.StrStuStatus == "在校" ? 1 : 2,
                    parent_name = studentModel.ParentName,


                };
                if (studentModel.ParentMobile != "")
                {
                    editModel.parent_phone = studentModel.ParentMobile;
                }
                else
                {
                    editModel.parent_phone = null;
                }

                string data = JsonHelper.ToJson(editModel);
                var result = Request<ReqStudentModel>("/api/student/addStudent", data, "添加学生");
                if (result.Item1)
                {
                    ShowDialogView("添加成功!");
                    GetStudentList(1);
                    studentView.UpdatePager();
                }
                else
                {
                    if (result.Item2 != null)
                        ShowDialogView(result.Item2.msg);
                }
            }



        }


        private void DeleteStudent()
        {
            //if (string.IsNullOrEmpty(studentModel.StuName))
            //{
            //    ErrorMsg.LoginMobileError = "学生姓名不能为空";
            //    return;
            //}

        }

        public void getGradesList()
        {
            StuClasses = new ObservableCollection<CommonModel>();

            ReqDelStudentModel model = new ReqDelStudentModel();

            model.token = HuiZeeducation.Instance.UserInfo.token;


            string data = JsonHelper.ToJson(model);
            var result = Request<List<ReqGradesList>>("/api/grades/classlist", data, "获取班级列表");
            if (result.Item1)
            {
                foreach (var item in result.Item2.data)
                {
                    CommonModel common = new CommonModel
                    {
                        Index = item.class_id,
                        Title = item.grade_text,

                    };
                    StuClasses.Add(common);


                }


            }
            else
            {
                if (result.Item2 != null)
                    ShowDialogView(result.Item2.msg);
            }

        }


        public void DeleteStudent(string Id)
        {

            if (string.IsNullOrWhiteSpace(Id))
            {
                //ErrorMsg.LoginMobileError = "学生姓名不能为空";
                return;
            }

            ReqDelStudentModel model = new ReqDelStudentModel();
            model.id = Id;
            model.token = HuiZeeducation.Instance.UserInfo.token;


            string data = JsonHelper.ToJson(model);
            var result = Request<ReqStudentModel>("/api/student/delStudent", data, "删除学生");
            if (result.Item1)
            {
                ShowDialogView("删除成功!");
                GetStudentList(1);
                studentView.UpdatePager();

            }
            else
            {
                if (result.Item2 != null)
                    ShowDialogView(result.Item2.msg);
            }

        }



        public void DownLoadTemp()
        {

            string path = SaveFile();
            if (string.IsNullOrWhiteSpace(path))
            {
                ShowDialogView("请选择下载路径!");
                return;
            }

            ReqDelStudentModel model = new ReqDelStudentModel();
            //model.id = Id;
            model.token = HuiZeeducation.Instance.UserInfo.token;


            string data = JsonHelper.ToJson(model);
            string parm = "?token=" + HuiZeeducation.Instance.UserInfo.token;

            var result = Request2<ReqDownStudentModel>("/api/student/downXls", data, "下载模板");
            //string parm = "?token=" + HuiZeeducation.Instance.UserInfo.token + "&ids=" + Ids;
            var result2 = RequestFile(result.Item2.data.ToString(), "下载模板", path);


            if (result.Item1)
            {
                ShowDialogView("下载成功!");
                //return result;
            }
            else
            {

                //return "";
            }

        }
        /// <summary>
        /// 导入
        /// </summary>
        public void ImportFile()
        {
            try
            {
                string path = SelectFile2();
                if (string.IsNullOrWhiteSpace(path))
                {
                    ShowDialogView("请选择文件!");
                    return;
                }
                string loadpath = UploadFile(path);

                int index = loadpath.IndexOf("/zh");
                ReqImportModel model = new ReqImportModel
                {
                    file = loadpath.Substring(loadpath.IndexOf("/zh"), (loadpath.Trim().Length - loadpath.IndexOf("/zh"))),
                    token = HuiZeeducation.Instance.UserInfo.token,
                };
                string data = JsonHelper.ToJson(model);
                var result = Request<ReqStudentModel>("/api/student/import", data, "一键导入");
                if (result.Item1)
                {
                    ShowDialogView("一键导入成功!");
                    //return result;
                }
                else
                {

                    //return "";
                }
            }
            catch
            {
                ShowDialogView("一键导入失败!");

            }

        }
        /// <summary>
        /// 导出
        /// </summary>
        public void ExportFile(int type, string Ids)
        {
            if (string.IsNullOrWhiteSpace(Ids) && type == 1)
            {
                ShowDialogView("请选择导出哪些学生!");
                return;
            }
            string path = SaveFile();

            if (string.IsNullOrWhiteSpace(path))
            {
                ShowDialogView("请选择保存路径!");
                return;
            }

            ReqExportModel model = new ReqExportModel();

            model.token = HuiZeeducation.Instance.UserInfo.token;

            if (type == 2)
            {
                Ids = "all";
                model.ids = "all";
            }
            else
            {
                Ids = Ids;
                model.ids = Ids;
            }
            string data = JsonHelper.ToJson(model);
            var result = Request2<ReqDownStudentModel>("/api/student/export", data, "下载模板");
            //string parm = "?token=" + HuiZeeducation.Instance.UserInfo.token + "&ids=" + Ids;
            var result2 = RequestFile(result.Item2.data.ToString(), "下载模板", path);
            if (result.Item1 && result2)
            {

                ShowDialogView("导出成功!");
                //return result;
            }
            else
            {
                //ShowDialogView(result.Item2.msg);
                //return "";
            }



        }



        private string UploadFile(string path)
        {
            if (string.IsNullOrWhiteSpace(path))
            {
                ShowDialogView("请选择上传文件!");
                return "";
            }
            ReqUploadModel model = new ReqUploadModel();

            model.token = HuiZeeducation.Instance.UserInfo.token;
            string data = JsonHelper.ToJson(model);
            var result = Upload<ResUploadModel>("/api/common/oss_upload", data, "上传文件", path);
            if (result.Item1)
            {
                ShowDialogView("导入成功!");
                return result.Item2.data.url;
            }
            else
            {
                return "";
            }



        }








        private String singleRadio;
        /// <summary>
        /// 单选框相关
        /// </summary>
        public String SingleRadio
        {
            get { return singleRadio; }
            set { singleRadio = value; RaisePropertyChanged(() => SingleRadio); }
        }

        private Boolean isSingleRadioCheck;
        /// <summary>
        /// 单选框是否选中
        /// </summary>
        public Boolean IsSingleRadioCheck
        {
            get { return isSingleRadioCheck; }
            set { isSingleRadioCheck = value; RaisePropertyChanged(() => IsSingleRadioCheck); }
        }


    }
}
